<!DOCTYPE html>
<html>

<head>
    <title>Customize your own components</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/dat.gui@0.7.6/build/dat.gui.min.js"></script>
    <link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maptalks/dist/maptalks.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/maptalks/dist/maptalks.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/three@0.97.0/build/three.min.js"></script>
    <script type="text/javascript"
        src="https://cdn.jsdelivr.net/npm/three@0.97.0/examples/js/libs/stats.min.js"></script>
    <!-- <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lz-string@1.4.4/libs/lz-string.min.js"></script> -->
    <script type="text/javascript" src="../dist/maptalks.three.js"></script>
    <script type="text/javascript" src="js/geoutil.js"></script>
    <!-- <script type="text/javascript" src="buildings.js"></script> -->
    <style>
        html,
        body {
            margin: 0px;
            height: 100%;
            width: 100%;
        }

        #map {
            width: 100%;
            height: 700px;
            background-color: #000;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>

        var map = new maptalks.Map("map", {
            center: [115.63373210417001, 34.87688357015699],
            zoom: 4,
            pitch: 40,
            // bearing: 180,
            centerCross: true,
            doubleClickZoom: false,
            // baseLayer: new maptalks.TileLayer('tile', {
            //     urlTemplate: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
            //     subdomains: ['a', 'b', 'c', 'd'],
            //     attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>'
            // })
        });

        // the ThreeLayer to draw buildings
        var threeLayer = new maptalks.ThreeLayer('t', {
            forceRenderOnMoving: true,
            forceRenderOnRotating: true,
            // animation: true
        });
        var stats;
        threeLayer.prepareToDraw = function (gl, scene, camera) {
            stats = new Stats();
            stats.domElement.style.zIndex = 100;
            document.getElementById('map').appendChild(stats.domElement);

            addLines();
        };
        threeLayer.addTo(map);


        var material = new THREE.LineBasicMaterial({
            linewidth: 1,
            color: 'rgb(13,141,255)',
            opacity: 0.12,
            transparent: true,
            blending: THREE.AdditiveBlending
        });

        // var lineMaterial = new THREE.LineBasicMaterial({
        //     linewidth: 1,
        //     color: '#0d37ff',
        //     opacity: 0.1,
        //     transparent: true,
        //     blending: THREE.AdditiveBlending
        // });
        var lines;

        function addLines() {
            // data from https://github.com/maptalks/maptalks.odline
            fetch('./data/lines.json').then(function (res) {
                return res.json();
            }).then(function (geojson) {
                var lineStrings = geojson.map(function (feature) {
                    var coordinates = feature.coordinates;
                    var [from, to] = coordinates;
                    var lnglats = [[parseFloat(from[0]), parseFloat(from[1])], [parseFloat(to[0]), parseFloat(to[1])]]
                    return new maptalks.LineString(lnglats);
                });

                var timer = 'generate line time';
                console.time(timer);
                var list = [];
                lineStrings.forEach(lineString => {
                    list.push({
                        lineString,
                        len: lineLength(lineString)
                    });
                });
                list = list.sort(function (a, b) {
                    return b.len - a.len
                });

                var offset = Infinity;
                lines = list.slice(0, offset).map(d => {
                    var line = new ArcLine(d.lineString, {
                        altitude: 0,
                        height: d.len / 3
                    }, material, threeLayer)
                    return line;
                });

                console.log('lines.length:', lines.length);
                console.timeEnd(timer);
                threeLayer.addMesh(lines);
                initGui();
                // threeLayer.config('animation', true);
                animation();
            })
        }

        function animation() {
            // layer animation support Skipping frames
            if (!map.isInteracting()) {
                threeLayer._needsUpdate = !threeLayer._needsUpdate;
                if (threeLayer._needsUpdate) {
                    threeLayer._renderer.clearCanvas();
                    threeLayer.renderScene();
                }
            } else {
                threeLayer._renderer.clearCanvas();
                threeLayer.renderScene();
            }
            stats.update();
            requestAnimationFrame(animation);
        }


        function initGui() {
            var params = {
                add: true,
                color: material.color.getStyle(),
                show: true,
                opacity: material.opacity,
                altitude: 0
            };
            var gui = new dat.GUI();
            gui.add(params, 'add').onChange(function () {
                if (params.add) {
                    threeLayer.addMesh(lines);
                } else {
                    threeLayer.removeMesh(lines);
                }
            });
            gui.addColor(params, 'color').name('line color').onChange(function () {
                material.color.set(params.color);
                lines.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, 'opacity', 0, 1).onChange(function () {
                material.opacity = params.opacity;
                lines.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, 'show').onChange(function () {
                lines.forEach(function (mesh) {
                    if (params.show) {
                        mesh.show();
                    } else {
                        mesh.hide();
                    }
                });
            });
            gui.add(params, 'altitude', 0, 300000).onChange(function () {
                lines.forEach(function (mesh) {
                    mesh.setAltitude(params.altitude);
                });
            });
        }


        //default values
        var OPTIONS = {
            height: 0,
            altitude: 0
        };


        /**
         * custom component
         * */

        class ArcLine extends maptalks.BaseObject {
            constructor(lineString, options, material, layer) {
                options = maptalks.Util.extend({}, OPTIONS, options, { layer, lineString });
                super();
                //Initialize internal configuration
                // https://github.com/maptalks/maptalks.three/blob/1e45f5238f500225ada1deb09b8bab18c1b52cf2/src/BaseObject.js#L135
                this._initOptions(options);

                const { altitude, height } = options;
                const points = getArcPoints(lineString, layer.distanceToVector3(height, height).x, layer);
                const positions = getLinePosition(points, layer).positions;
                const geometry = new THREE.BufferGeometry();
                geometry.addAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
                this._createLine(geometry, material);

                //set object3d position
                const z = layer.distanceToVector3(altitude, altitude).x;
                const center = lineString.getCenter();
                const v = layer.coordinateToVector3(center, z);
                this.getObject3d().position.copy(v);
            }

        }


        function getArcPoints(lineString, height, layer) {
            const lnglats = [];
            if (Array.isArray(lineString)) {
                lnglats.push(lineString[0], lineString[lineString.length - 1]);
            } else if (lineString instanceof maptalks.LineString) {
                const coordinates = lineString.getCoordinates();
                lnglats.push(coordinates[0], coordinates[coordinates.length - 1]);
            }
            const [first, last] = lnglats;
            let center;
            if (Array.isArray(first)) {
                center = [first[0] / 2 + last[0] / 2, first[1] / 2 + last[1] / 2];
            } else if (first instanceof maptalks.Coordinate) {
                center = [first.x / 2 + last.x / 2, first.y / 2 + last.y / 2];
            }
            const centerPt = layer.coordinateToVector3(lineString.getCenter());
            const v = layer.coordinateToVector3(first).sub(centerPt);
            const v1 = layer.coordinateToVector3(last).sub(centerPt);
            const vh = layer.coordinateToVector3(center, height).sub(centerPt);
            const ellipse = new THREE.CatmullRomCurve3([v, vh, v1], false, 'catmullrom');
            const points = ellipse.getPoints(40);
            return points;
        }
    </script>
</body>

</html>